package com.walle.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zhangjiapeng
 * @Package com.walle.nio
 * @Description: ${todo}
 * @date 2019/1/21 14:50
 */
public class TimeClient implements Runnable {

    private Selector selector;

    private SocketChannel socketChannel;

    private boolean stop;


    public static void main(String[] args) throws IOException {
        new Thread(new TimeClient()).start();
    }


    public TimeClient() {
        try {
            selector  = Selector.open();
            socketChannel  = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        doConnect();
        try {
            while (!stop){
                selector.select(1000);
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectedKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    handleInput(key);
                }
            }
            selector.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private  void handleInput(SelectionKey selectionKey) throws IOException {
        if(selectionKey.isValid()){
            if(selectionKey.isConnectable()){
               if(socketChannel.finishConnect()){
                   socketChannel.register(selector,SelectionKey.OP_READ);
                   doWrite(socketChannel);
               }
            }
            if(selectionKey.isReadable()){
                SocketChannel socket = (SocketChannel) selectionKey.channel();
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                int readBytes = socket.read(buffer);
                if (readBytes > 0) {
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    String msg = new String(bytes,"UTF-8");
                    System.out.println("received time :" + msg);
                    this.stop = true;
                }else if(readBytes < 0){
                    selectionKey.cancel();
                    socket.close();
                }else{
                }
            }
        }
    }
    private void doConnect(){
        try {
            if(socketChannel.connect(new InetSocketAddress("127.0.0.1",9999))){
                socketChannel.register(selector,SelectionKey.OP_READ);
            }else{
                socketChannel.register(selector,SelectionKey.OP_CONNECT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doWrite(SocketChannel socket) throws IOException {
        String currentTime = "现在几点了";
        byte[] bytes = currentTime.getBytes();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(bytes);
        buffer.flip();
        socket.write(buffer);
    }
}
